import { ref } from 'vue'
import { defineStore } from 'pinia'
import { asyncRoutes, constantRoutes } from '@/router'
import type { RouteRecordRaw } from 'vue-router'
import Cookies from 'js-cookie'
import { mapToString, stringToMap } from '@/utils'

export const usePermissionStore = defineStore('permission', () => {
  const routes = ref<RouteRecordRaw[]>([])
  const tagRoutes = ref<Map<string, string>>(stringToMap(Cookies.get('tagRoutes') || '{"/home": "首页"}'))
  function generateRoutes() {
    return new Promise<RouteRecordRaw[]>((resolve) => {
      routes.value = constantRoutes.concat(asyncRoutes)
      resolve(asyncRoutes)
    })
  }

  // 添加快捷导航
  function addTag(path: string, title: string) {
    tagRoutes.value.set(path, title)
    Cookies.set('tagRoutes', mapToString(tagRoutes.value))
  }

  // 删除快捷导航
  function deleteTag(path: string) {
    tagRoutes.value.delete(path)
    Cookies.set('tagRoutes', mapToString(tagRoutes.value))
  }

  return { routes, tagRoutes, generateRoutes, addTag, deleteTag }
})
